<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\admin\controller;

use app\common\controller\Backend;
use ChuanglanSmsHelper\ChuanglanSmsApi;

class Reminder extends Backend
{
    //crontab -u yizhimao 0 0 12 * * ? php think admin/crontab/exec
    protected $noNeedLogin = ['exec'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];

    public function exec(){
        $db=db('userinfo');
        $result=$db->select();
        foreach ($result as $item){
            $date2=date('Y',time()).'-'.date('m-d',strtotime($item['birthday']));
            $date1=date('Y',time()).'-'.date('m-d',time());
            //echo $date1;
            //echo "<br>";
            //echo $date2;
            $bool=$this->diffDay($date2,$date1);

            if ($bool){
                $mobile=db('user')->where('id',$item['uid'])->value('mobile');
                if ($mobile){
                    $this->send($mobile);
                    echo $item['turename']."生日提醒已经发送<br>";
                }else{
                    echo "您不是我们平台的普通会员，请先绑定手机号码";
                }
            }else{
                echo $item['turename'].'没到生日前三天呢'."<br>";
            }
        }
    }
    private function diffDay($date1,$date2){
        $strdata1=strtotime($date1);
        $strdata2=strtotime($date2);
        if($strdata1<$strdata2){
            return false;
        }else{
            $diff=($strdata1-$strdata2)/86400;
            return $diff== 3 ? true:false;
        }
    }
    private function send($mobile){
        header("Content-type:text/html; charset=UTF-8");
        //Loader::import('ChuanglanSmsHelper\ChuanglanSmsApi','extend/');
        $clapi  = new ChuanglanSmsApi();

        $code = mt_rand(100000,999999);

        if(!preg_match('/^1[3,5,7,8]\d{9}/',$mobile)){
            return json(['code'=>400,'msg'=>'电话号码非法']);
        }

        $result = $clapi->sendSMS($mobile,'【庄浪融媒】尊敬的依之猫会员，您今年的生日将于3天后到来，请你到依之猫门店领取生日礼物，您的领取短信验证码是'.$code );

        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                return json(['code'=>200,'msg'=>'发送成功','data'=>$output['code']]);
            }else{
                return json(['code'=>400,'msg'=>$output['errorMsg']]);
            }
        }else{
            return json(['code'=>500,'msg'=>'发送短信服务器异常']);
        }
    }
}